﻿namespace MultipleMonitorVideo.Utilities
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    using Caliburn.Micro;

    using Modules;
    using Screen = System.Windows.Forms.Screen;

    public class ModuleManager
    {
        public ModuleManager(IList<Module> modules)
        {
            this.Modules = modules;

            foreach (Module module in modules)
            {
                //module.ControlViewModel;
                ScreenExtensions.TryActivate(module.ControlViewModel);
            }
        }

        public IList<Module> Modules
        {
            get;
            private set;
        }

        public Module GetModule(Type moduleType)
        {
            return this.Modules.FirstOrDefault(module => module.GetType() == moduleType);
        }

        public Module FindModuleWithScreen(Screen screen)
        {
            return this.Modules.FirstOrDefault(module => module.Screen != null && module.Screen.Equals(screen));
        }

        public void UpdateCurrentModule(Type moduleType, Screen screen)
        {
            Module newModule = this.GetModule(moduleType);

            if (newModule == null)
            {
                return;
            }

            Module oldModule = this.FindModuleWithScreen(screen);

            if (oldModule != null)
            {
                oldModule.SetScreen(null);
            }

            newModule.SetScreen(screen);
        }

        public void DisableAllModules()
        {
            foreach (Module module in this.Modules)
            {
                module.SetScreen(null);
            }
        }
    }
}
